<template>
  <div class="session-manage">
    <el-card>
      <div class="card-header">
        <h2>上机管理</h2>
      </div>

      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="开始上机" name="start">
          <!-- 开始上机表单保持不变 -->
          <el-form
            :model="startSessionForm"
            :rules="startRules"
            ref="startFormRef"
            label-width="100px"
          >
            <el-form-item label="学生ID" prop="student_id">
              <el-select
                v-model="startSessionForm.student_id"
                placeholder="请选择学生"
                clearable
                style="width: 100%"
                :change="handleStudentChange"
                :loading="loadingStudents"
              >
                <el-option
                  v-for="student in students"
                  :key="student.id_"
                  :label="`${student.name} (学号：${student.student_id})`"
                  :value="student.id_"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="机房" prop="room_id">
              <el-select
                v-model="startSessionForm.room_id"
                placeholder="请选择机房"
                clearable
                style="width: 100%"
                @change="handleRoomChange"
              >
                <el-option
                  v-for="room in rooms"
                  :key="room.id_"
                  :label="`${room.name} (${room.location})`"
                  :value="room.id_"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="机器" prop="machine_id">
              <el-select
                v-model="startSessionForm.machine_id"
                placeholder="请选择机器"
                clearable
                style="width: 100%"
                :disabled="!startSessionForm.room_id"
                :loading="loadingMachines"
              >
                <el-option
                  v-for="machine in availableMachines"
                  :key="machine.id_"
                  :label="`${machine.machine_number} - ${getMachineStatusText(
                    machine.status
                  )}`"
                  :value="machine.id_"
                >
                </el-option>
              </el-select>
              <div
                v-if="
                  availableMachines.length === 0 && startSessionForm.room_id
                "
                class="no-machines"
              >
                该机房暂无可用机器
              </div>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="handleStartSession"
                :loading="starting"
                :disabled="!canStartSession"
              >
                开始上机
              </el-button>
              <el-button @click="resetStartForm">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 学生信息预览 -->
          <el-card v-if="studentInfo" class="student-preview" header="学生信息">
            <p><strong>姓名:</strong> {{ studentInfo.name || "未知" }}</p>
            <p><strong>学号:</strong> {{ studentInfo.student_id }}</p>
            <p>
              <strong>余额:</strong> {{ formatCurrency(studentInfo.balance) }}
            </p>
          </el-card>
        </el-tab-pane>

        <el-tab-pane label="正在上机" name="active">
          <div class="table-actions">
            <el-button
              type="primary"
              @click="fetchActiveSessions"
              :loading="loading"
            >
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <span class="session-count"
              >共 {{ activeSessions.length }} 个活跃会话</span
            >
          </div>
          <el-table
            :data="activeSessions"
            border
            v-loading="loading"
            empty-text="暂无活跃会话"
          >
            <el-table-column
              prop="id_"
              label="会话ID"
              width="100"
            ></el-table-column>
            <el-table-column label="学生信息" min-width="150">
              <template #default="scope">
                <div>
                  <div>ID: {{ getActiveStudentId(scope.row) }}</div>
                  <div>姓名: {{ getActiveStudentName(scope.row) }}</div>
                  <div>学号: {{ getActiveStudentNumber(scope.row) }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="机器信息" min-width="150">
              <template #default="scope">
                <div>
                  <div>编号: {{ getActiveMachineNumber(scope.row) }}</div>
                  <div>机房: {{ getActiveRoomName(scope.row) }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="start_time" label="开始时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.start_time) }}
              </template>
            </el-table-column>
            <el-table-column label="已用时间" width="120">
              <template #default="scope">
                {{ formatDuration(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column label="预估费用" width="120">
              <template #default="scope">
                ¥{{ calculateActiveCost(scope.row).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button
                  type="danger"
                  size="small"
                  @click="handleEndSession(scope.row)"
                >
                  结束上机
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="历史记录" name="history">
          <div class="table-actions">
            <el-input
              v-model="searchStudentId"
              placeholder="输入学生ID、姓名或学号查询"
              style="width: 300px; margin-right: 10px"
              clearable
              @clear="fetchHistorySessions"
            ></el-input>
            <el-button
              type="primary"
              @click="fetchHistorySessions"
              :loading="loading"
            >
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <span class="session-count"
              >共 {{ filteredHistorySessions.length }} 条历史记录</span
            >
          </div>
          <el-table
            :data="filteredHistorySessions"
            border
            v-loading="loading"
            empty-text="暂无历史记录"
          >
            <el-table-column
              prop="id_"
              label="会话ID"
              width="100"
            ></el-table-column>
            <el-table-column label="学生信息" min-width="150">
              <template #default="scope">
                <div>
                  <div>ID: {{ scope.row.student_id }}</div>
                  <div>姓名: {{ getHistoryStudentName(scope.row) }}</div>
                  <div>学号: {{ getHistoryStudentNumber(scope.row) }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="机器信息" min-width="150">
              <template #default="scope">
                <div>
                  <div>编号: {{ getHistoryMachineNumber(scope.row) }}</div>
                  <div>机房: {{ getHistoryRoomName(scope.row) }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="start_time" label="开始时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.start_time) }}
              </template>
            </el-table-column>
            <el-table-column prop="end_time" label="结束时间" width="180">
              <template #default="scope">
                {{
                  scope.row.end_time
                    ? formatDateTime(scope.row.end_time)
                    : "进行中"
                }}
              </template>
            </el-table-column>
            <el-table-column label="时长" width="100">
              <template #default="scope">
                {{ formatSessionDuration(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column label="费率" width="100">
              <template #default="scope">
                {{ formatCurrency(scope.row.hourly_rate) }}
              </template>
            </el-table-column>
            <el-table-column label="总费用" width="120">
              <template #default="scope">
                {{ formatCurrency(scope.row.total_cost) }}
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getSessionStatusType(scope.row.status)">
                  {{ getSessionStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, onUnmounted } from "vue";
import {
  startSession,
  endSession,
  getActiveSessions,
  getHistorySessions,
} from "../api/sessions";
import { getComputerRooms } from "../api/rooms";
import { getAvailableMachines } from "../api/machine";
import { getStudents } from "../api/students";
import { ElMessage, ElMessageBox } from "element-plus";
import { Refresh } from "@element-plus/icons-vue";

// 状态管理
const activeTab = ref("start");
const rooms = ref([]);
const availableMachines = ref([]);
const activeSessions = ref([]);
const historySessions = ref([]);
const students = ref([]);
const searchStudentId = ref("");
const timer = ref(null);
const loading = ref(false);
const starting = ref(false);
const loadingMachines = ref(false);
const loadingStudents = ref(false);
const studentInfo = ref(null);

// 表单引用
const startFormRef = ref(null);

// 表单数据
const startSessionForm = ref({
  student_id: "",
  room_id: null,
  machine_id: null,
});

// 计算属性 - 是否可以开始上机
const canStartSession = computed(() => {
  return (
    startSessionForm.value.student_id &&
    startSessionForm.value.room_id &&
    startSessionForm.value.machine_id
  );
  // &&
  //  studentInfo.value &&
  //  studentInfo.value.balance > 0
});

// 表单验证规则
const startRules = ref({
  student_id: [{ required: true, message: "选择学生", trigger: "blur" }],
  room_id: [{ required: true, message: "请选择机房", trigger: "blur" }],
  machine_id: [{ required: true, message: "请选择机器", trigger: "blur" }],
});

// 计算属性 - 过滤历史记录
const filteredHistorySessions = computed(() => {
  if (!searchStudentId.value) return historySessions.value;

  const searchTerm = searchStudentId.value.toLowerCase();
  return historySessions.value.filter((session) => {
    const studentIdMatch = session.student_id.toString().includes(searchTerm);
    const studentNameMatch = getHistoryStudentName(session)
      .toLowerCase()
      .includes(searchTerm);
    const studentNumberMatch = getHistoryStudentNumber(session)
      .toLowerCase()
      .includes(searchTerm);

    return studentIdMatch || studentNameMatch || studentNumberMatch;
  });
});

// ========== 历史记录数据访问方法 (SessionHistoryItem 结构) ==========
const getHistoryStudentName = (session) => {
  return session.student_name || "未知";
};

const getHistoryStudentNumber = (session) => {
  return session.student_number || "未知";
};

const getHistoryMachineNumber = (session) => {
  return session.machine_number || "未知";
};

const getHistoryRoomName = (session) => {
  return session.room_name || "未知";
};

// ========== 正在上机数据访问方法 (活跃会话结构) ==========
const getActiveStudentId = (session) => {
  // 优先使用 student_id 字段，如果没有则从 student 对象获取
  return session.student_id || session.student?.id_ || "未知";
};

const getActiveStudentName = (session) => {
  // 活跃会话可能没有扁平化的 student_name，需要从 student 对象获取
  return session.student_name || session.student?.name || "未知";
};

const getActiveStudentNumber = (session) => {
  // 活跃会话可能没有扁平化的 student_number，需要从 student 对象获取
  return session.student_number || session.student?.student_id || "未知";
};

const getActiveMachineNumber = (session) => {
  // 活跃会话可能没有扁平化的 machine_number，需要从 machine 对象获取
  return session.machine_number || session.machine?.machine_number || "未知";
};

const getActiveRoomName = (session) => {
  // 活跃会话可能没有扁平化的 room_name，需要从 machine.room 对象获取
  return session.room_name || session.machine?.room?.name || "未知";
};

// 格式化金额
const formatCurrency = (value) => {
  if (value === undefined || value === null) return "¥0.00";
  return "¥" + parseFloat(value).toFixed(2);
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return "";
  try {
    return new Date(dateTime).toLocaleString("zh-CN");
  } catch (error) {
    return "日期格式错误";
  }
};

// 格式化会话时长
const formatSessionDuration = (session) => {
  if (session.duration_minutes) {
    const hours = Math.floor(session.duration_minutes / 60);
    const minutes = session.duration_minutes % 60;
    return hours > 0 ? `${hours}小时${minutes}分钟` : `${minutes}分钟`;
  }

  if (session.start_time && session.end_time) {
    try {
      const start = new Date(session.start_time).getTime();
      const end = new Date(session.end_time).getTime();
      const minutes = Math.floor((end - start) / (1000 * 60));
      const hours = Math.floor(minutes / 60);
      const mins = minutes % 60;
      return hours > 0 ? `${hours}小时${mins}分钟` : `${mins}分钟`;
    } catch (error) {
      return "计算错误";
    }
  }

  return "进行中";
};

// 格式化实时时长
const formatDuration = (session) => {
  if (!session.start_time) return "0分钟";

  try {
    const startTime = new Date(session.start_time).getTime();
    const now = new Date().getTime();
    const minutes = Math.floor((now - startTime) / (1000 * 60));

    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;

    return hours > 0 ? `${hours}小时${mins}分钟` : `${mins}分钟`;
  } catch (error) {
    return "时间计算错误";
  }
};

// 获取机器状态文本
const getMachineStatusText = (status) => {
  const statusMap = {
    available: "可用",
    in_use: "使用中",
    maintenance: "维修中",
  };
  return statusMap[status] || status;
};

// 获取会话状态文本
const getSessionStatusText = (status) => {
  const statusMap = {
    active: "进行中",
    completed: "已完成",
    cancelled: "已取消",
  };
  return statusMap[status] || status;
};

// 获取会话状态类型
const getSessionStatusType = (status) => {
  const typeMap = {
    active: "warning",
    completed: "success",
    cancelled: "danger",
  };
  return typeMap[status] || "info";
};

// 计算活跃会话实时费用
const calculateActiveCost = (session) => {
  if (!session.start_time) return 0;

  try {
    const startTime = new Date(session.start_time).getTime();
    const now = new Date().getTime();
    const hours = (now - startTime) / (1000 * 60 * 60);
    const hourlyRate =
      session.hourly_rate || session.machine?.room?.hourly_rate || 5;
    return hours * hourlyRate;
  } catch (error) {
    return 0;
  }
};

// 获取机房列表
const fetchRooms = async () => {
  try {
    const response = await getComputerRooms();
    rooms.value = response.data;
  } catch (error) {
    ElMessage.error(
      "获取机房列表失败: " + (error.response?.data?.detail || error.message)
    );
    console.error("获取机房列表失败:", error);
  }
};

const fetchStudents = async () => {
  try {
    const response = await getStudents();
    students.value = response.data;
  } catch (error) {
    ElMessage.error(
      "获取学生列表失败: " + (error.response?.data?.detail || error.message)
    );
    console.error("获取学生列表失败:", error);
  }
};

// 处理学生ID输入
const handleStudentChange = async (value) => {
  if (!value) {
    students.value = [];
    startSessionForm.value.student_id = '';
    return;
  }

  loadingStudents.value = true;
  try {
    const response = await getStudents();
    students.value = response.data;
    startSessionForm.value.student_id = '';
    if (students.value.length === 0) {
      ElMessage.warning("未找到学生");
    }
  } catch (error) {
    students.value = [];
    // 学生不存在是正常情况，不显示错误
    if (error.response?.status !== 400 && error.response?.status !== 404) {
      console.error("获取学生信息失败:", error);
    }
  } finally {
    loadingStudents.value = false;
  }
};

// 处理机房切换
const handleRoomChange = async (roomId) => {
  if (!roomId) {
    availableMachines.value = [];
    startSessionForm.value.machine_id = null;
    return;
  }

  loadingMachines.value = true;
  try {
    const response = await getAvailableMachines(roomId);
    availableMachines.value = response.data;
    // 重置机器选择
    startSessionForm.value.machine_id = null;

    if (availableMachines.value.length === 0) {
      ElMessage.warning("该机房暂无可用机器");
    }
  } catch (error) {
    ElMessage.error(
      "获取可用机器失败: " + (error.response?.data?.detail || error.message)
    );
    console.error("获取可用机器失败:", error);
    availableMachines.value = [];
  } finally {
    loadingMachines.value = false;
  }
};

// 获取活跃会话
const fetchActiveSessions = async () => {
  loading.value = true;
  try {
    const response = await getActiveSessions();
    activeSessions.value = response.data;
  } catch (error) {
    ElMessage.error(
      "获取活跃会话失败: " + (error.response?.data?.detail || error.message)
    );
    console.error("获取活跃会话失败:", error);
    activeSessions.value = [];
  } finally {
    loading.value = false;
  }
};

// 获取历史会话
const fetchHistorySessions = async () => {
  loading.value = true;
  try {
    const response = await getHistorySessions(0, 100);
    historySessions.value = response.data;
  } catch (error) {
    ElMessage.error(
      "获取历史会话失败: " + (error.response?.data?.detail || error.message)
    );
    console.error("获取历史会话失败:", error);
    historySessions.value = [];
  } finally {
    loading.value = false;
  }
};

// 重置开始表单
const resetStartForm = () => {
  startSessionForm.value = {
    student_id: "",
    room_id: null,
    machine_id: null,
  };
  studentInfo.value = null;
  if (startFormRef.value) {
    startFormRef.value.clearValidate();
  }
};

// 处理标签页点击
const handleTabClick = (tab) => {
  if (tab.paneName === "active") {
    fetchActiveSessions();
  } else if (tab.paneName === "history") {
    fetchHistorySessions();
  }
};

// 开始上机
const handleStartSession = async () => {
  if (!startFormRef.value) return;

  try {
    // 验证表单
    await startFormRef.value.validate();

    // 检查学生余额
    if (studentInfo.value && studentInfo.value.balance <= 0) {
      ElMessage.warning("学生余额不足，请先充值");
      return;
    }

    starting.value = true;

    // 准备请求数据 - 确保类型正确
    const sessionData = {
      student_id: parseInt(startSessionForm.value.student_id),
      machine_id: parseInt(startSessionForm.value.machine_id),
    };

    const response = await startSession(sessionData);
    ElMessage.success(`上机开始成功，会话ID: ${response.data.session_id}`);

    // 重置表单
    resetStartForm();

    // 立即刷新所有相关数据
    await Promise.all([fetchActiveSessions(), fetchHistorySessions()]);

    // 刷新可用机器列表
    if (startSessionForm.value.room_id) {
      await handleRoomChange(startSessionForm.value.room_id);
    }

    // 自动切换到活跃会话标签页
    activeTab.value = "active";
  } catch (error) {
    console.error("开始上机失败详情:", {
      status: error.response?.status,
      data: error.response?.data,
      message: error.message,
    });

    let errorMessage = "开始上机失败";
    if (error.response?.data?.detail) {
      if (Array.isArray(error.response.data.detail)) {
        errorMessage +=
          ": " + error.response.data.detail.map((d) => d.msg).join(", ");
      } else {
        errorMessage += ": " + error.response.data.detail;
      }
    }

    ElMessage.error(errorMessage);
  } finally {
    starting.value = false;
  }
};

// 结束上机
const handleEndSession = async (session) => {
  try {
    const estimatedCost = calculateActiveCost(session);
    await ElMessageBox.confirm(
      `确定要结束会话 ${session.id_} 吗？\n学生: ${getActiveStudentName(
        session
      )}\n预估费用: ¥${estimatedCost.toFixed(2)}`,
      "确认结束上机",
      {
        confirmButtonText: "确认结束",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const response = await endSession(session.id_);
    ElMessage.success(
      `上机结束成功，总费用: ¥${response.data.total_cost.toFixed(2)}`
    );

    // 立即刷新所有相关数据
    await Promise.all([fetchActiveSessions(), fetchHistorySessions()]);

    // 刷新当前机房可用机器
    if (startSessionForm.value.room_id) {
      await handleRoomChange(startSessionForm.value.room_id);
    }
  } catch (error) {
    if (error === "cancel") {
      return;
    }
    ElMessage.error(error.response?.data?.detail || "结束上机失败");
    console.error("结束上机失败:", error);
  }
};

// 实时更新活跃会话
const startRealTimeUpdate = () => {
  timer.value = setInterval(() => {
    if (activeTab.value === "active") {
      fetchActiveSessions();
    }
  }, 30000); // 每30秒更新一次
};

// 清理定时器
const clearRealTimeUpdate = () => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
};

// 监听标签页切换
watch(activeTab, (newVal) => {
  if (newVal === "active") {
    fetchActiveSessions();
    startRealTimeUpdate();
  } else if (newVal === "history") {
    fetchHistorySessions();
    clearRealTimeUpdate();
  } else {
    clearRealTimeUpdate();
  }
});

onMounted(() => {
  fetchRooms();
  fetchActiveSessions();
  fetchHistorySessions();
  fetchStudents();
  if (activeTab.value === "active") {
    startRealTimeUpdate();
  }
});

// 组件卸载时清理定时器
onUnmounted(() => {
  clearRealTimeUpdate();
});
</script>

<style scoped>
.card-header {
  margin-bottom: 20px;
}

.session-manage {
  padding: 20px;
}

.table-actions {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.session-count {
  color: #909399;
  font-size: 14px;
  margin-left: auto;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

.no-machines {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
}

.student-preview {
  margin-top: 20px;
  background-color: #f8f9fa;
}

.student-preview p {
  margin: 5px 0;
}

:deep(.el-table .cell) {
  word-break: break-word;
}
</style>
